//
//  JANetworkTool+News.m
//  网易新闻
//
//  Created by Arvin on 17/3/19.
//  Copyright © 2017年 Arvin. All rights reserved.
//

#import "JANetworkTool+News.h"
#import "JANewsModel.h"
#import <YYModel.h>

@implementation JANetworkTool (News)

-(void)requestNewList:(NSString *)tid callBack:(void (^)(NSArray *))callBack{
    
    NSString *urlStr = [NSString stringWithFormat:@"http://c.m.163.com/nc/article/headline/%@/0-20.html",tid];
    
    [[JANetworkTool sharedTool]reqeusWith:urlStr method:@"GET" parameters:nil callBack:^(id response) {
        //判断服务器是否返回nil,如果返回nil,就直接回调,告诉控制器回调失败
        if(response)
        {
            NSArray *dicArr = response[tid];
            NSArray *modelArry = [NSArray yy_modelArrayWithClass:[JANewsModel class] json:dicArr];
            callBack(modelArry);
        }
        else
        {
            callBack(nil);
        }
    }];
}


-(void)requestNewsDetail:(NSString *)docId callBack:(void (^)(NSString *bodyString))callBack{
    //拼接新闻详情页的接口
    NSString *urlString = [NSString stringWithFormat:@"http://c.m.163.com/nc/article/%@/full.html",docId];
    
    //使用网络中间层的方法,发起新闻详情页数据的请求
    [[JANetworkTool sharedTool]reqeusWith:urlString method:@"GET" parameters:nil callBack:^(id response) {
        
        //详情页的数据字典
        NSDictionary *bodyDic = response[docId];
        //详细页的正文的html的字符串
        NSString *bodyStr = bodyDic[@"body"];
        //正文所有图片信息的字典数组
        NSArray *imageArr = bodyDic[@"img"];
        //正文的样子,从本地加载
        NSString *css = [NSString stringWithContentsOfURL:[[NSBundle mainBundle] URLForResource:@"news.css" withExtension:nil]encoding:NSUTF8StringEncoding error:NULL];
         //将所有的注释掉的 `<!--IMG#0-->` 格式的图片字符串,替换成hmtl中 img标签
        for (NSDictionary *img in imageArr) {
            NSString *imgHtml = [NSString stringWithFormat:@"<img src=%@>",img[@"src"]];
            bodyStr = [bodyStr stringByReplacingOccurrencesOfString:img[@"ref"] withString:imgHtml];
        }
        
          //将css与body的正文拼接成一个完整和html字符串
        NSString *html = [NSString stringWithFormat:@"%@%@",css,bodyStr];
        
        //回调,将html传给控制器展示
        callBack(html);
    
    }];
}

@end
